import logging
from datetime import datetime

from django.forms import model_to_dict
from django.utils import timezone

from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from rest_framework import viewsets, status
from rest_framework.response import Response
from rest_framework.views import APIView

from utils.alipay import Alipay
from .models import UserProfile
from .serializers import UserSerializer
from django.conf import settings
from utils import deepseek, common
import requests

from apps.Conf.models import SystemSetting

logger = logging.getLogger('order')

# Create your views here.
def get_content(birth_date,birth_time,user_sex,address,type_param,prompt):
    api_key = settings.DEEPSEEK_API_KEYS
    if not api_key:
        return HttpResponse("缺少 API Key，请在 settings.DEEPSEEK_API_KEY 或环境变量中配置。", status=500)

    # 支持从请求参数传入 prompt，否则使用默认示例
    prompt = (
        f"""
        用户信息：
        - 查询方向：{type_param}
        - 出生日期：{birth_date}
        - 出生时间：{birth_time}
        - 性别：{user_sex}
        - 出生地区 {address}
        {prompt}
        """
    )
    try:
        content = deepseek._call_deepseek(prompt, api_key)
        return content
    except requests.Timeout:
        return HttpResponse("调用超时：请增大读取超时或降低生成长度。", status=504)
    except requests.HTTPError as e:
        status = e.response.status_code if getattr(e, "response", None) is not None else 502
        body = None
        try:
            if getattr(e, "response", None) is not None:
                body = e.response.text
        except Exception:
            body = None
        msg = f"HTTP错误：状态码 {status}"
        if status == 401:
            msg += "（可能是API Key错误或过期）"
        elif status == 429:
            msg += "（请求频率超限，请稍后再试）"
        elif status in [500, 502, 503, 504]:
            msg += "（服务端异常，可重试）"
        if body:
            msg += f"；响应体：{body[:500]}"
        return HttpResponse(msg, status=status)
    except Exception as e:
        return HttpResponse(f"调用失败：{e}", status=502)


class UserViewSet(viewsets.ModelViewSet):
    queryset = UserProfile.objects.all()
    serializer_class = UserSerializer

    # def perform_create(self, serializer):
    def create(self, request, *args, **kwargs):
        # 1. 获取前端传入的原始 content 值（如果前端没传，用空字符串避免报错）
        #获得用户查询的项目
        type_param=request.GET.get('type','求姻缘')
        birth_date = self.request.data.get('user_birthday_date', '')
        birth_time = self.request.data.get('user_birthday_time', '')
        user_sex=self.request.data.get('user_sex', '')
        address=self.request.data.get('user_address', '')

        system=SystemSetting.objects.get(id=1)
        prompt=system.content
        mount=system.mount
        #获得用户的ip地址
        user_ip = self.request.META.get('REMOTE_ADDR')
        result=get_content(birth_date,birth_time,user_sex,address,type_param,prompt)
        #result='测试一下'
        serializer = self.get_serializer(data={
            'user_birthday_date': birth_date,
            'user_birthday_time': birth_time,
            'user_sex': user_sex,
            'content': result,
            'user_ip': user_ip,
            'address':address,
            'type':type_param,
            'order_mount': mount,
        })
        serializer.is_valid(raise_exception=True)  # 数据校验（比如字段格式是否正确）
        saved_instance = serializer.save()

        return Response({
            'code': 200,
            'msg': '提交成功',
            'result': result,  # 直接返回分析结果
            'data_id': saved_instance.id  # 返回存入数据的 id
        }, status=status.HTTP_201_CREATED)


#调用支付宝
class AlipayAPIView(APIView):
    def get(self,request):
        data_id=request.GET.get('data_id',None)

        try:
            #取得商品表的信息
            user_profile=UserProfile.objects.get(id=data_id)
        except:
            error_msg = "404,订单表取值失败1" + str(data_id)
            return Response({"error":error_msg}, status=status.HTTP_404_NOT_FOUND)
        #自定义一个订单号
        out_trade_no="pay"+datetime.now().strftime('%Y%m%d%H%M%S')+common.get_random_codes(4)

        #将支付信息存如订单表中
        try:
            user_profile.order_sn=out_trade_no
            user_profile.save()

        except Exception as e:
            # 打印具体错误信息（在控制台/日志中查看）
            # 1. 记录错误信息到日志文件
            logger.error("订单创建失败详情2：%s", str(e))  # 记录错误描述
            print("订单创建失败详情：", str(e))
            return Response({"error": "405,订单创建失败:"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        #执行支付宝
        alipay = Alipay()
        try:
            out_trade_no=out_trade_no
            total_amount=str(user_profile.order_mount)
            subject='服务费'
            body="支付宝支付"
            product_code='FAST_INSTANT_TRADE_PAY'
            passback_params=out_trade_no
            pay_url=alipay.trade_page(out_trade_no,total_amount,subject,body,product_code,passback_params,data_id)
            return Response(pay_url)

        except Exception as e:
            # 打印具体错误信息（在控制台/日志中查看）
            # 1. 记录错误信息到日志文件
            logger.error("订单创建失败详情3：%s", str(e))  # 记录错误描述
            return Response({"error":"406,支付失败"}, status=status.HTTP_404_NOT_FOUND)

#支付宝回调判断
class AlipayCallbackAPIView(APIView):
    def post(self,request):
        #将返回值改成字典
        params=request.POST.dict()
        #去除sign和sign_type字段
        sign = params.pop('sign')
        del params['sign_type']
        # 对字段进行排序
        sorted_list = sorted([(k, v) for k, v in params.items()])
        unsigned_string = '&'.join(f"{k}={v}" for k, v in sorted_list)
        print(unsigned_string)
        alipay = Alipay()
        #支付宝回调验证
        if not alipay.verify_sign(unsigned_string,sign):
            print("407,支付接口回调失败")
            return Response({"error":"407,支付接口回调失败"}, status=status.HTTP_400_BAD_REQUEST)

        #本地数据验证
        #验证订单号
        try:
            user_profile=UserProfile.objects.get(order_sn=params.get('out_trade_no'))
        except:
            print('410')
            return Response({"error":"410"}, status=status.HTTP_404_NOT_FOUND)
        if params.get('total_amount') != str(user_profile.order_mount):
            print('411')
            return Response({"error":"411"}, status=status.HTTP_404_NOT_FOUND)
        if params.get('seller_id') != settings.ALIPAY_SELLER_ID:
            print('412')
            return Response({"error":"406,<UNK>"}, status=status.HTTP_404_NOT_FOUND)
        if params.get('app_id') != settings.ALIPAY_APP_ID:
            print('413')
            return Response({"error":"406,<UNK>"}, status=status.HTTP_404_NOT_FOUND)
        if params.get('trade_status') not in ['TRADE_SUCCESS','TRADE_FINISHED']:
            print('414')
            return Response({"error":"406,<UNK>"}, status=status.HTTP_404_NOT_FOUND)

        #全部通过后，执行业务
        #更新order表，order在前面已经实例化过了
        try:
            user_profile.trade_no = params.get('trade_no')
            user_profile.pay_status = params.get('trade_status')
            user_profile.pay_time = timezone.now()
            user_profile.save()
        except Exception as e:
            # 返回错误信息和 500 状态码（服务器内部错误）
            return Response(
                {"error": f"更新支付信息失败：{str(e)}"},  # 错误描述（转为字符串）
                status=status.HTTP_500_INTERNAL_SERVER_ERROR  # 明确状态码
            )
        print('支付成功')
        return HttpResponse("success")

def pay_success(request,id):
    user=UserProfile.objects.get(id=id)
    return render(request,"pay.html",{"user":user})

# class UserViewDisplay(viewsets.ModelViewSet):
#     queryset = UserProfile.objects.all()
#     serializer_class = UserSerializer


def UserViewDisplay(request,id):
    userData=UserProfile.objects.get(order_sn=id)
    user_data = model_to_dict(userData)
    return JsonResponse({
        "data": user_data,
        "message": "查询成功"
    })